package com.mall.web.annotation;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.mall.constant.UserConstant;
import com.mall.pojo.User;
import com.mall.web.util.HttpUrlTypeUtil;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.WebUtil;

/**
 * 运营后台权限判断，没有用户信息同步的功能。需要配合其他aop来使用
 * 
 * @author Administrator
 *
 */
@Aspect
@Component
public class AdminSecurityAop {

	public final String noPerssionUrl = "/perssion/noPerssion.htm";

	@Around("@annotation(com.mall.web.annotation.AdminSecurity)")
	public Object doCheck(ProceedingJoinPoint joinPoint) throws Throwable {

		String methodName = joinPoint.getSignature().getName();
		Method method = joinPoint.getTarget().getClass().getMethod(methodName,
				((MethodSignature) joinPoint.getSignature()).getParameterTypes());
		AdminSecurity securityAnnotation = method.getAnnotation(AdminSecurity.class);
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();
		User user = WebUtil.getCurrentUser(request);
		int needUserType = securityAnnotation.userType();// 用户权限等级
		if (needUserType < UserConstant.TYPE_KEFU) {// 设置默认值。不能低于客服的级别
			needUserType = UserConstant.TYPE_KEFU;
		}
		if (user == null || user.getType() == null || user.getType() < needUserType) {
			
			if (HttpUrlTypeUtil.isWeiShang(request)) {
				response.sendRedirect(HttpUtil.URL_USER_LOGIN_WEISHANG);
			}else{
				response.sendRedirect(HttpUtil.URL_USER_LOGIN);
			}
			return null;
		}

		return joinPoint.proceed();
	}
}
